﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DLL;
using PagedList;
using CommonHelpers;
using QuanLyBanLe.Constants;

namespace QuanLyBanLe.Benefit
{
    public partial class FormSellStatistics : Form
    {
        private BillService m_BillService;
        private ProductTypeService m_ProductTypeService;
        private ProducerService m_ProducerService;
        private ReturnProductService m_ReturnProductService;
        private List<pSellStatistics_Result> m_SellStatistics;
        private int m_PageNumber;
        private int m_PageSize;
        private int m_MaxPage;
        private int m_TotalRecord;
        private bool m_EnabledEvent;
        private int m_TotalSale = 0;
        private int m_TotalDiscount = 0;
        private int m_TotalBenefit = 0;
        private int m_TotalInput = 0;
        private bool m_Filterd;

        public FormSellStatistics()
        {
            InitializeComponent();
            m_BillService = new BillService();
            m_ProductTypeService = new ProductTypeService();
            m_ProducerService = new ProducerService();
            m_ReturnProductService = new ReturnProductService();
            m_SellStatistics = new List<pSellStatistics_Result>();
            m_EnabledEvent = false;
            m_Filterd = false;
            m_PageSize = 20;
            m_PageNumber = 1;
        }

        private void FormSellStatistics_Load(object sender, EventArgs e)
        {
            IList<ProductType> productTypes = m_ProductTypeService.GetProductTypes();
            ProductType allProductType = new ProductType();
            allProductType.Id = 0;
            allProductType.Name = "Tất cả";
            productTypes.Insert(0, allProductType);
            cboProductType.DataSource = productTypes;
            cboProductType.ValueMember = "Id";
            cboProductType.DisplayMember = "Name";

            IList<Producer> producers = m_ProducerService.GetProducers();
            Producer allProducer = new Producer();
            allProducer.Id = 0;
            allProducer.Name = "Tất cả";
            producers.Insert(0, allProducer);
            cboProducer.DataSource = producers;
            cboProducer.ValueMember = "Id";
            cboProducer.DisplayMember = "Name";

            dtpFromDate.Value = DateTime.Now;
            dtpToDate.Value = DateTime.Now;

            dtgSellProduct.AutoGenerateColumns = false;

            lblTotalPrice.Text = "0 Đ";
            lblTotalBenefit.Text = "0 Đ";
            lblTotalDis.Text = "0 Đ";
            lblTotalInput.Text = "0 Đ";
            lblTotalReturn.Text = "0 Đ";
            lblTotalReturnCalculated.Text = "0 Đ";
            lblRealTotalPrice.Text = "0 Đ";
            BindDataSource();

            this.Text += FormMain.GetShopInfo();
        }

        private void btnStatistics_Click(object sender, EventArgs e)
        {
            m_PageNumber = 1;
            BindDataSource();
            m_Filterd = true;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            m_PageNumber = 1;
            ChangePage();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_PageNumber > 1 ? m_PageNumber - 1 : m_PageNumber;
            ChangePage();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_PageNumber < m_MaxPage ? m_PageNumber + 1 : m_PageNumber;
            ChangePage();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            m_PageNumber = m_MaxPage;
            ChangePage();
        }

        private void mnrPageIndex_ValueChanged(object sender, EventArgs e)
        {
            if (m_EnabledEvent)
            {
                m_PageNumber = Convert.ToInt32(mnrPageIndex.Value);
                ChangePage();
            }
        }

        private void GetData()
        {
            if (m_PageNumber < 1)
            {
                m_PageNumber = 1;
            }
            DateTime fromDate = dtpFromDate.Value;
            DateTime toDate = dtpToDate.Value;

            int? productTypeId = null;
            if (cboProductType.SelectedValue != null)
            {
                productTypeId = Convert.ToInt32(cboProductType.SelectedValue);
                if (productTypeId == 0)
                {
                    productTypeId = null;
                }
            }

            int? producerId = null;
            if (cboProducer.SelectedValue != null)
            {
                producerId = Convert.ToInt32(cboProducer.SelectedValue);
                if (producerId == 0)
                {
                    producerId = null;
                }
            }

            string productName = null;
            if (!string.IsNullOrEmpty(txtProductName.Text))
            {
                productName = txtProductName.Text;
            }

            m_SellStatistics = m_BillService.SellStatistics(fromDate, toDate,
                productTypeId, producerId, productName,
                out m_TotalSale, out m_TotalDiscount, out m_TotalBenefit, out m_TotalInput);
        }

        private void BindDataSource()
        {
            m_EnabledEvent = false;
            GetData();
            IPagedList<pSellStatistics_Result> pagedList = m_SellStatistics.ToPagedList(m_PageNumber, m_PageSize);
            AddRecordsToDataGrid(pagedList.ToList());
            m_TotalRecord = pagedList.TotalItemCount;
            m_MaxPage = pagedList.PageCount;
            lblTotalPrice.Text = m_TotalSale.ToMoney();
            lblTotalBenefit.Text = m_TotalBenefit.ToMoney();
            lblTotalDis.Text = m_TotalDiscount.ToMoney();
            lblTotalInput.Text = m_TotalInput.ToMoney();

            // get total return product
            var totalReturnResult = m_ReturnProductService.GetTotalReturn(dtpFromDate.Value, dtpToDate.Value);
            int totalReturn = totalReturnResult.TotalReturn.HasValue ? totalReturnResult.TotalReturn.Value : 0;
            int totalReturnCalculated = totalReturnResult.TotalReturnCalculated.HasValue ? totalReturnResult.TotalReturnCalculated.Value : 0;
            lblTotalReturn.Text = totalReturn.ToMoney();
            lblTotalReturnCalculated.Text = totalReturnCalculated.ToMoney();
            int realTotal = m_TotalSale - totalReturn + totalReturnCalculated;
            lblRealTotalPrice.Text = realTotal.ToMoney();

            if (m_TotalRecord > 0)
            {
                lblTotalPage.Text = "/" + m_MaxPage.ToString();
                m_EnabledEvent = false;
                mnrPageIndex.Minimum = 1;
                mnrPageIndex.Enabled = true;
                mnrPageIndex.Maximum = m_MaxPage;
                mnrPageIndex.Value = m_PageNumber;
                SetEnabledForPagingNavigator();
            }
            else
            {
                m_PageNumber = 0;
                mnrPageIndex.Minimum = 0;
                mnrPageIndex.Value = 0;
                mnrPageIndex.Enabled = false;
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnLast.Enabled = false;
                btnNext.Enabled = false;
            }
            m_EnabledEvent = true;
        }

        private void SetEnabledForPagingNavigator()
        {
            if (m_PageNumber == m_MaxPage)
            {
                if (m_PageNumber == 1)
                {
                    btnFirst.Enabled = false;
                    btnPrev.Enabled = false;
                    btnLast.Enabled = false;
                    btnNext.Enabled = false;
                }
                else
                {
                    btnFirst.Enabled = true;
                    btnPrev.Enabled = true;
                    btnLast.Enabled = false;
                    btnNext.Enabled = false;
                }
            }
            else if (m_PageNumber == 1)
            {
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnLast.Enabled = true;
                btnNext.Enabled = true;
            }
            else
            {
                btnFirst.Enabled = true;
                btnPrev.Enabled = true;
                btnLast.Enabled = true;
                btnNext.Enabled = true;
            }
        }

        private void ChangePage()
        {
            IPagedList<pSellStatistics_Result> pagedList = m_SellStatistics.ToPagedList(m_PageNumber, m_PageSize);
            AddRecordsToDataGrid(pagedList.ToList());

            // Prevent changePage call second time from mnrPageIndex_ValueChanged
            m_EnabledEvent = false;
            mnrPageIndex.Value = m_PageNumber;
            m_EnabledEvent = true;

            m_TotalRecord = pagedList.TotalItemCount;
            m_MaxPage = pagedList.PageCount;
            lblTotalPage.Text = "/" + m_MaxPage.ToString();

            SetEnabledForPagingNavigator();
        }

        private void AddRecordsToDataGrid(List<pSellStatistics_Result> sells)
        {
            dtgSellProduct.Rows.Clear(); // Clear old data
            int i = 0;
            foreach (pSellStatistics_Result sell in sells)
            {
                dtgSellProduct.Rows.Add(1);
                DataGridViewRow row = dtgSellProduct.Rows[i];
                row.Cells["colRowNumber"].Value = ((m_PageNumber - 1) * m_PageSize) + i + 1;
                row.Cells["colProductType"].Value = sell.ProductTypeName;
                row.Cells["colProducer"].Value = sell.ProducerName;
                row.Cells["colProduct"].Value = sell.Name;                
                row.Cells["colAmount"].Value = sell.Amount;
                row.Cells["colRemainAmount"].Value = sell.RemainAmount;
                row.Cells["colTotalSalePrice"].Value = sell.TotalSalePrice;
                row.Cells["colTotalInputPrice"].Value = sell.TotalInput.Value.ToMoney();
                row.Cells["colTotalBenefit"].Value = sell.TotalBenefit;
                row.Cells["colTotalDiscount"].Value = sell.TotalDiscount;
                i++;
            }
        }

        private SortType GetSortType(DataGridViewColumn column)
        {
            SortType sortType = SortType.ASC;
            if (column.Tag != null)
            {
                SortType currentSortType = (SortType)column.Tag;
                if (currentSortType == SortType.ASC)
                {
                    sortType = SortType.DES;
                }
                else
                {
                    sortType = SortType.ASC;
                }
            }
            return sortType;
        }

        private void dtgSellProduct_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dtgSellProduct.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.NotSortable)
            {
                return;
            }

            SortType sortType = GetSortType(dtgSellProduct.Columns[e.ColumnIndex]);
            dtgSellProduct.Columns[e.ColumnIndex].Tag = sortType;

            if (e.ColumnIndex == dtgSellProduct.Columns["colProductType"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.ProductTypeName).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.ProductTypeName).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colProducer"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.ProducerName).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.ProducerName).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colProduct"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.Name).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.Name).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colRemainAmount"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.RemainAmount).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.RemainAmount).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colAmount"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.Amount).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.Amount).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colTotalSalePrice"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.TotalSalePrice).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.TotalSalePrice).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colTotalInputPrice"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.TotalInput).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.TotalInput).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colTotalBenefit"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.TotalBenefit).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.TotalBenefit).ToList();
                }
            }

            if (e.ColumnIndex == dtgSellProduct.Columns["colTotalDiscount"].Index)
            {
                if (sortType == SortType.ASC)
                {
                    m_SellStatistics = m_SellStatistics.OrderBy(x => x.TotalDiscount).ToList();
                }
                else
                {
                    m_SellStatistics = m_SellStatistics.OrderByDescending(x => x.TotalDiscount).ToList();
                }
            }

            AddRecordsToDataGrid(m_SellStatistics.ToPagedList(m_PageNumber, m_PageSize).ToList());
        }

        private void btnViewReport_Click(object sender, EventArgs e)
        {
            FormSellStatisticsReport frm = new FormSellStatisticsReport(m_SellStatistics);
            frm.ShowDialog();
        }

        private void btnClearFilter_Click(object sender, EventArgs e)
        {
            dtpFromDate.Value = DateTime.Now;
            dtpToDate.Value = DateTime.Now;
            cboProductType.SelectedValue = 0;
            cboProducer.SelectedValue = 0;
            txtProductName.Text = "";
            m_Filterd = false;
            m_PageNumber = 1;
            BindDataSource();
        }

        private void cbo_KeyDown(object sender, KeyEventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (cbo.DroppedDown)
            {
                cbo.DroppedDown = false;
            }
        }
    }
}
